<template>
  <div class="productList">
    <navBar title="商品列表" />

    <!-- tab栏 -->
    <van-tabs @click="tabCkilck" class="activeTab">
      <van-tab title="综合" />
      <van-tab>
        <template #title>
          价格
          <van-icon name="sort" />
        </template>
      </van-tab>
      <van-tab title="新品" />
    </van-tabs>

    <!-- 商品列表 -->
    <div class="content">
      <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <shop :list="productsList" :pricestate="false" />
    </van-list>
    </div>

    <!-- 空状态 -->
    <van-empty description="没有更多了" v-if="!productsList.length" />
  </div>
</template>

<script>
import shop from '@/components/shop'
import {
  getProducts,
} from '@/api/product'

export default {
  components: {
    shop,
  },
  data() {
    return {
      productsList: [], // 商品列表
      query: null, // 查询参数
      total: 0, // 数据量
      loading: false,
      finished: false,
      state: true, // 价格排序
      page: {
        limit: 10,
        page: 1,
      }
    }
  },
  created() {
    const { query } = this.$route
    this.query = query
    this.getProducts()
  },
  methods: {
    // 获取商品列表
    async getProducts() {
      const { data } = await getProducts({
        ...this.page,
        ...this.query
      })
      this.productsList.push(...data.content)
      this.total = data.totalElements || 0
      if(this.productsList.length >= this.total) this.finished = true
    },

    // 上拉加载更多
    onLoad() {
      this.page.page += 1
      this.getProducts()
      this.loading = false
    },

    // tab栏点击事件
    tabCkilck(e) {
      switch (e) {
        case 0: // 综合排列
          this.page = { limit: 10, page: 1 }
          this.productsList = []
          this.getProducts()
          break;
        case 1: // 新品排列
          this.page = { limit: 10, page: 1, priceOrder: this.state ? 'asc' : 'desc' }
          this.productsList = []
          this.getProducts()
          this.state = !this.state
          break;
        case 2: // 新品排列
          this.page = { limit: 10, page: 1, news: 1 }
          this.productsList = []
          this.getProducts()
          break;
      }
    },
  },
}
</script>
<style lang="scss" scoped>
.productList {
  text-align: left;
  .activeTab {
    margin: 5px 10px 5px;
  }
  .content {
    margin: 5px;
  }
}
</style>
<style scoped>
.activeTab >>> .van-tab--active {
  color: #ee0a24;
}
.activeTab >>> .van-tabs__line {
  display: none;
}
</style>